package jzqb.controller.admin;

import cnki.tpi.base.DataSourceManager;
import haha.life.common.CutPageBean;
import haha.life.common.MonitorTypeTool;
import haha.life.common.PermissionTypeTool;
import haha.life.normal.FileUtil;
import haha.life.normal.FileuploadUtils;
import haha.life.normal.RandomUtils;
import io.swagger.annotations.Api;
import jzqb.annotation.PermissionCheck.PermissionCheck;
import jzqb.bo.AdminQueryBo;
import jzqb.common.Result;
import jzqb.po.CGPo;
import jzqb.service.AdminCGService;
import jzqb.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/adminCG")
@Api(tags = "后台研究成果控制层")
public class AdminCGController {

    @Autowired
    private AdminCGService adminCGService;

    @Value("${filePath.fileTemPResource}")
    private String fileTemPResource;

    @Value("${filePath.coverTemPResource}")
    private String coverTemPResource;

    @Value("${filePath.qbcgCoverPath}")
    private String qbcgCoverPath;

    @Autowired
    private MonitorService monitorService;

    //新建研究成果
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @PostMapping(value = "insertCG")
    public Result insertCG(@RequestBody CGPo cgPo,HttpServletRequest request){
        Boolean result = null;
        result = adminCGService.insertCG(cgPo);
        if(result){
            Boolean insertRes = true;
            try {
                insertRes = monitorService.record(request,new MonitorTypeTool().getAddFile(),cgPo.getTitle(), "研究成果库");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            if(insertRes){
                return Result.succ("新建研究成果成功");
            }
        }
        return Result.fail("新建研究成果失败");
    }

    //修改研究成果
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @PostMapping(value = "updateCG")
    public Result updateCG(@RequestBody CGPo cgPo,HttpServletRequest request){
        Boolean result = null;
        result = adminCGService.updateCG(cgPo);
        if(result){
            Boolean insertRes = true;
            try {
                insertRes = monitorService.record(request,new MonitorTypeTool().getEditFile(),cgPo.getTitle(), "研究成果库");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            if(insertRes){
                return Result.succ("修改研究成果成功");
            }
        }
        return Result.fail("修改研究成果失败");
    }

    //删除研究成果
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @PostMapping(value = "deleteCG")
    public Result deleteCG(@RequestBody CGPo cgPo,HttpServletRequest request){
        Boolean result = adminCGService.deleteCG(cgPo);
        if(result){
            Boolean insertRes = true;
            try {
                insertRes = monitorService.record(request,new MonitorTypeTool().getDeleteFile(),cgPo.getTitle(), "研究成果库");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            if(insertRes){
                return Result.succ("删除研究成果成功");
            }
        }
        return Result.fail("删除研究成果失败");
    }

    //查询研究成果
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @GetMapping(value = "queryCG")
    public Result queryCG(
            @RequestParam("searchWay") String searchWay,
            @RequestParam("keyWord") String keyWord,
            @RequestParam("standardType[]") String[] standardType,
            @RequestParam("classification") String classification,
            @RequestParam("page") int page,
            @RequestParam("pageSize") int pageSize
    ){
        AdminQueryBo bo = new AdminQueryBo();
        bo.setSearchWay(searchWay);
        bo.setKeyWord(keyWord);
        bo.setClassification(classification);
        bo.setStart((page - 1) * pageSize);
        bo.setEnd(pageSize);
        bo.setStandardType(standardType);
        List<CGPo> list = adminCGService.queryCG(bo);
        Integer total = adminCGService.count(bo).intValue();
        CutPageBean cutPageBean = new CutPageBean<>();
        cutPageBean.initCutPage(total, pageSize, list);
        return Result.succ(cutPageBean);
    }

    //文件临时上传
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @RequestMapping(value = "/fileTempUpload")
    public Result fileTempUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        //获取文件名
        String cover = request.getParameter("cover");
        String fileName =file.getOriginalFilename();
        String randDir = RandomUtils.getDirByName(fileName);
        String coverName = cover;
        CGPo cgPo = new CGPo();
        cgPo.setDigitFileName(fileName);
        try {
            String filePath = new File(fileTemPResource,randDir).toString();
            FileUtil.saveFile(file, filePath, fileName);//执行保存(文件,目录,文件名)
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
            if (!"".equals(fileName) && "PDF".equals(fileType)){
                coverName = fileName.substring(0,fileName.lastIndexOf("."))+".png";//命名截图
                String fileDir = FileUtil.calculateAbstractPath(fileName,fileTemPResource);
                String coverDir = FileUtil.calculateAbstractPath(coverName,coverTemPResource);
                FileuploadUtils.pdfToPhoto(fileDir, coverDir);
                cgPo.setCover(coverName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(cgPo);
    }

    //图片临时上传
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @RequestMapping(value = "/imageTempUpload")
    public Result imageTempUpload(@RequestParam("file") MultipartFile file) {
        String fileName =file.getOriginalFilename();
        String randDir = RandomUtils.getDirByName(fileName);
        String basePath= coverTemPResource;
        String filePath = new File(basePath,randDir).toString();
        try {
            //执行保存(文件,目录,文件名)
            FileUtil.saveFile(file, filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(fileName);
    }

    //展示研究成果封面
    @PermissionCheck(permissionTypeList  ={PermissionTypeTool.business_mgt})
    @RequestMapping(value ="/getImage",produces="application/json;charset=UTF-8")
    public Result createFolw(HttpServletRequest request, HttpServletResponse response) {
        String cover = request.getParameter("cover");
        String type = request.getParameter("type");
        if("temp".equals(type)){
            type = coverTemPResource;
        }else{
            type = qbcgCoverPath;
        }
        String path = FileUtil.calculateAbstractPath(cover,type);
        byte[] imageBinary = FileuploadUtils.getImageBinary(path);
        return  Result.succ(imageBinary);
    }
}

